window.addEventListener('load',function() {

	var submit = document.getElementsByName('submit')[0];
	
	var username = document.getElementById('login_username');
	var password = document.getElementById('login_password');
		
	var errormessage = "Kombinasi username dan password yang kamu masukkan tidak cocok";
		
	//$('#errortext').append(errormessage);
		
	document.getElementById('login_form').onsubmit = function() {
		$('#login_username').attr("disabled", true);
		$('#login_password').attr("disabled", true);
		var result;
		$.get( "http://estudiahapid.ap01.aws.af.cm/services/login.php?username=" + username.value + "&password=" + password.value, function( data ) {
			result = JSON.parse(data);
			if (result["status"] == "success") {
				//alert("login success");
				localStorage.setItem("estudia_user", username.value);
				localStorage.setItem("estudia_level", result["level"]);
				localStorage.setItem("estudia_exp", result["exp"]);
			} else {
				//alert("login fail");
				$('#errortext').empty();
				$('#errortext').append(errormessage);
				$('#errortext').show();
				$('#login_username').attr("disabled", false);
				$('#login_password').attr("disabled", false);
			}
			
		}).done(function() {
			if (result["status"] == "success") {
				$.get( "http://estudiahapid.ap01.aws.af.cm/services/getachievment.php?username=" + username.value, function( data ) {
					var response = JSON.parse(data);
					if (response["status"] ==" empty") {
						
					} else {
						localStorage.setItem("estudia_achievment_length", response["length"]);
						for(var i = 0; i <= 11; i++) {
							if (i < 10) {
								localStorage.setItem("estudia_achievment_b0" + i, response["b0" + i]);
							} else {
								localStorage.setItem("estudia_achievment_b" + i, response["b" + i]);
							}
						}
					}
				}).done( function() {
					window.location.href = 'home.html';
				});
			}
		}).fail(function() {
			alert("Get failed");
		});
		
		/*
		for (var i = 1; i <= 11; i++) {
			localStorage.setItem("estudia_achievment_" + i, i);
		}// */
		
		//

		return false;
	};	
	
});
